#-*-coding:utf-8-*-
from flask import Flask, render_template, request, redirect
from flask import session, jsonify
from query_elec import query_elec_fun
from query_cet import cet_result
from db_models import *
from openid import OffiAcco, addopenid
import urllib
import requests

app.secret_key = "jwrm3ru89324jiojs"  # session密钥
app.permanent_session_lifetime = 7200  # session过期时间为2小时
# 获取openid的接口
openid_api_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxae665dcf8fe8ad28&redirect_uri=\
http%3a%2f%2fweixin.l.ncuhome.cn%3a5050%2fgetopenid&response_type=code&scope=snsapi_base&state="
getopenid = {
    "elec": openid_api_url + "http%3a%2f%2fweixin.l.ncuhome.cn%3a5050%2felec%3f%0a" + "#wechat_redirect",
    "cet": openid_api_url + "http%3a%2f%2fweixin.l.ncuhome.cn%3a5050%2fcet%3f%0a" + "#wechat_redirect"
}

#~~~~~~~~~~~~~~~~~~~~~~~查电部分~~~~~~~~~~~~~~~~~~~~~~~


@app.route('/elec')
def user_auth():
    """查电"""
    openid = request.args.get("openid")
    if openid:
        session["openid"] = openid  # 添加或更新session
    else:  # 请求中无openid参数
        if "openid" in session:  # 检查session是否存在openid
            pass
        else:  # 不存在则重定向到获取openid的接口
            return redirect(getopenid["elec"])

    info = Openid.query.filter_by(
        openid=session["openid"]).first()  # 检查openid表中是否存在该openid
    if info is None:  # 如果不存在则添加到数据表中
        Add = Openid(openid=session["openid"])
        db.session.add(Add)
        db.session.commit()
        return render_template("elec_register.html", action="/elec/newuser")
    else:
        elec_user = Elec_Users.query.filter_by(id=info.id).first()
        if elec_user is None:
            return render_template("elec_register.html", action="/elec/newuser")
        dom_num = elec_user.room_num
        query_result = query_elec_fun(dom_num)  # 查询该宿舍的信息
        if query_result == "Timeout!":
            return render_template("error.html", state=u"连接超时")
        elif query_result == "NoFound":
            return render_template('elec_failed.html')
        else:
            check_result = Elec_Result.query.filter_by(
                room_num=dom_num).order_by(Elec_Result.id.desc()).first()
            AddNewResult = None  # 以下若干步用于将查询结果存入数据库
            if check_result:
                if query_result["new_reading"] != check_result.new_reading:  # 如果查表总读数不相同的
                    AddNewResult = Elec_Result(room_num=dom_num, used_elec=query_result['used_elec'], remaining_money=query_result[
                        'remaining_money'], remaining_elec=query_result['remaining_elec'],
                        remaining_time=query_result['remaining_time'], new_reading=query_result["new_reading"])
            else:  # 如果数据库中不存在这个宿舍的
                AddNewResult = Elec_Result(room_num=dom_num, used_elec=query_result['used_elec'], remaining_money=query_result['remaining_money'],
                                           remaining_elec=query_result[
                                               'remaining_elec'], remaining_time=query_result['remaining_time'],
                                           new_reading=query_result["new_reading"])
            if AddNewResult:
                db.session.add(AddNewResult)
                db.session.commit()
            return render_template('elec_result.html', used_elec=query_result['used_elec'], money=query_result['remaining_money'],
                                   electricty=query_result[
                                       'remaining_elec'], day=query_result['remaining_time'],
                                   check_time=query_result['check_time'], dom_num=dom_num)


@app.route('/elec/newuser', methods=['POST'])
def new_user():
    """新的查电用户"""
    try:
    dom_num = request.form["dom_num"]
    contact_info = request.form["contact_info"]
    true_input = dom_num and contact_info
    if (("openid" in session) and true_input):
        check = Openid.query.filter_by(
            openid=session["openid"]).first()  # 检查openid表中是否有该用户
        if not check:  # 如果不存在则添加到openid数据表中
            Add = Openid(openid=session["openid"])
            db.session.add(Add)
            db.session.commit()
            check = Openid.query.filter_by(openid=session["openid"]).first()

        che_elecu = Elec_Users.query.filter_by(
            id=check.id).first()  # 检查elec_users表是否已存在该用户
        if not che_elecu:
            if (("@" and ".") in contact_info):  # and ("." in contact_info))
                contact_way = "email"
            else:
                contact_way = "sms"
            NewUser = Elec_Users(id=check.id, room_num=dom_num,
                                 contact_info=contact_info, contact_way=contact_way)
            db.session.add(NewUser)
            db.session.commit()

            return redirect("/elec")
        else:
            return render_template("error.html", state=u"用户已存在")
    else:
        return render_template("error.html", state=u"获取用户资料失败,请重试")
    except:
        db.session.rollback()
        return render_template("error.html", state=u"服务器错误")


@app.route('/elec/update', methods=['GET', 'POST'])
def update_info():
    """查电用户更新信息"""
    try:
    if "openid" in session:
        if (request.method == "GET"):
            return render_template('elec_register.html', action="/elec/update")
        else:
            dom_num = request.form["dom_num"]
            contact_info = request.form["contact_info"]
            if dom_num and contact_info:
                if (("@" in contact_info) and ("." in contact_info)):
                    contact_way = "email"
                elif contact_info == ""：
                    contact_way = "no"
                else:
                    contact_way = "sms"
                check = Openid.query.filter_by(
                    openid=session["openid"]).first()  # 检查openid数据表
                if not check:  # 如果不存在则添加到openid数据表中
                    Add = Openid(openid=session["openid"])
                    db.session.add(Add)
                    db.session.commit()
                    check = Openid.query.filter_by(
                        openid=session["openid"]).first()
                upd_info = Elec_Users.query.filter_by(
                    id=check.id).first()  # 检查elec_users表是否存在该用户
                if upd_info:
                    upd_info.room_num = dom_num
                    upd_info.contact_info = contact_info
                    upd_info.contact_way = contact_way
                    db.session.commit()
                else:
                    return render_template("error.html", state=u"用户不存在，更新失败")
            else:
                return render_template("error.html", state=u"提交的数据无效")

    return redirect("/elec")
    except:
        db.session.rollback()
        return render_template("error.html", state=u"服务器错误")

#~~~~~~~~~~~~~~~~~~~~~~~四六级查询部分~~~~~~~~~~~~~~~~~~~~~~~


@app.route('/cet')
def index():
    """获取openid查询数据库，如果存在该用户，
    则返回准考证号，否则返回值为空的json字符串"""
    openid = request.args.get("openid")
    if openid:
        session["openid"] = openid  # 添加或更新session
    else:  # 请求中无openid参数
        if "openid" in session:  # 检查session是否存在openid
            pass
        else:  # 不存在则重定向到获取openid的接口
            return redirect(getopenid["cet"])
    zkzh = ''
    xm = ''
    user_openid = Openid.query.filter_by(openid=session["openid"]).first()
    if user_openid:  # 检查openid数据表
        cet_user = Cet_Users.query.filter_by(id=user_openid.id).first()
        if cet_user:
            zkzh = cet_user.examid
            xm = cet_user.name
        else:
            pass
    else:  # 添加到openid数据表
        Add = Openid(openid=session["openid"])
        db.session.add(Add)
        db.session.commit()
    return render_template("cet_main.html", zkzh=zkzh, name=xm)


@app.route('/cet/query', methods=["POST"])
def query():
    """根据表单提交的数据进行处理"""
    if "openid" not in session:
        return redirect(getopenid["cet"])
    else:
        user_openid = Openid.query.filter_by(
            openid=session["openid"]).first()  # 检查openid表
        if user_openid:
            pass
        else:
            Add = Openid(openid=session["openid"])
            db.session.add(Add)
            db.session.commit()
            user_openid = Openid.query.filter_by(
                openid=session["openid"]).first()
        data = request.json
        zkzh = data.get("zkzh")
        xm = data.get("xm")
        if (zkzh and xm):
            li = cet_result(zkzh, xm)  # 进行查询
            if li:
                if (li == "QueryFail"):
                    return jsonify(status="QueryFail")
                else:
                    user_info = Cet_Users.query.filter_by(
                        id=user_openid.id).first()
                    if user_info:  # 如果数据库中存在该用户，则更新
                        user_info.examid = zkzh
                        user_info.name = xm
                        db.session.commit()
                    else:  # 如果数据库中无该用户，则添加
                        NewUser = Cet_Users(
                            id=user_openid.id, examid=zkzh, name=xm)
                        db.session.add(NewUser)
                        db.session.commit()
                    return jsonify(xm=li[0], xx=li[1], kslb=li[2],
                                   zkzh=li[3], kssj=li[4], zf=li[5],
                                   tl=li[6], yd=li[7], xzfy=li[8], status='OK')
            else:
                return jsonify(status="NotFound")
        else:
            return jsonify(status="GetUserInfoError")


#~~~~~~~~~~~~~~~~~~~~~~~获取openid~~~~~~~~~~~~~~~~~~~~~~~

@app.route('/getopenid')
def get_openid():
    raw_redi_url = request.args.get("state")  # 获取需要回调的原始地址
    if raw_redi_url:
        redirect_url = urllib.unquote(raw_redi_url)  # 对回调地址进行url解码
        if "?" in redirect_url:
            main_redi_url = redirect_url.splite("?")[0]  # 有参数的则提前参数前的地址
        else:
            main_redi_url = redirect_url
    else:
        return jsonify(errmsg="invalid url")
    if main_redi_url in OffiAcco.permit_url:  # 检查地址是否为允许地址
        code = request.args.get("code")  # 获取微信用户对应的code
        url = OffiAcco.main_url
        args = {
            "appid": OffiAcco.appid,
            "secret": OffiAcco.secret,
            "code": code,
            "grant_type": "authorization_code"
        }
        try:
            # 尝试通过code换取用户的openid等json数据包
            response = requests.get(url, params=args, timeout=5)
        except requests.ConnectionError:  # 超时
            return jsonify(errmsg="timeout")

        openid = (response.json()).get("openid")
        if openid:
            redi_url = addopenid(redirect_url, openid)  # 将回调的地址接上openid
            return redirect(redi_url)
        else:
            return jsonify(errmsg="get openid failed")
    else:
        return jsonify(errmsg="url disallowed")


@app.errorhandler(404)
def Not_Found(e):
    return render_template("error.html", state=u"您访问的地址不存在"), 404


@app.errorhandler(500)
    def internal_error(e):
        return render_template('error.html', state=u"服务器繁忙"), 500
